package com.decent.ejfadmin.finance.dao;


import com.decent.ejfadmin.common.bean.*;
import com.decent.ejfadmin.common.enums.WithdrawLogTypeEnum;
import com.decent.ejfadmin.finance.dao.provider.SupplyFinanceDaoProvider;
import com.decent.ejfadmin.finance.request.RebateUserQueryParam;
import com.decent.ejfadmin.finance.request.WithdrawRecordQueryParam;
import com.decent.ejfadmin.finance.response.dto.RebateUserDto;
import com.decent.ejfadmin.finance.response.dto.WithdrawRecordDto;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.List;


/**
 * 供货系统资金管理
 *
 * @author 王元鑫
 * @date 2016/8/6
 */
@Mapper
@Repository
public interface SupplyFinanceDao {
    /**
     * 查询供货余额
     *
     * @param userId 会员id
     * @return 供货余额
     */
    @Select("select  userId,balance,version,freezebalance,balance-freezebalance actualBalance,commision, " +
            "freeze_commision freezeCommision ,commision- freeze_commision actualCommision  " +
            "from yuhuang_supply_balance where userId = #{userId} for update ")
    SupplyBalance querySupplyBalanceVersion(@Param("userId") Long userId);

    /**
     * 修改供货余额或者冻结金额
     *
     * @param balance 余额bean
     * @param money   金额
     * @param status  状态
     * @return 修改行数
     */
    @UpdateProvider(type = SupplyFinanceDaoProvider.class, method = "modifyBalance")
    int modifyBalance(@Param("balance") SupplyBalance balance, @Param("money") double money, @Param("status") Integer status);

    /**
     * 新增供货明细
     *
     * @param supplyConsumption 资金明细
     * @return 新增行数
     */
    @Insert("insert yuhuang_user_consumption (userId,consumeType,orderId,channel,money,balance,type) " +
            " values (#{supplyConsumption.userId},#{supplyConsumption.consumeType}," +
            " #{supplyConsumption.orderId},ifnull(#{supplyConsumption.channel},'结算'), " +
            " #{supplyConsumption.money},#{supplyConsumption.balance},#{supplyConsumption.type}) ")
    int createSupplyConsumption(@Param("supplyConsumption") SupplyConsumption supplyConsumption);

    /**
     * 修改佣金
     *
     * @param balance 余额bean
     * @param money   金额
     * @param status  状态
     * @return 修改行数
     */
    @UpdateProvider(type = SupplyFinanceDaoProvider.class, method = "modifyCommisionBalance")
    int modifyCommisionBalance(@Param("balance") SupplyBalance balance, @Param("money") double money, @Param("status") Integer status);

    /**
     * 创建供货余额
     *
     * @param id
     * @return
     */
    @Insert("insert into yuhuang_supply_balance (userId) values (#{id})")
    int createSupplyBalance(@Param("id") Long id);

    /**
     * 查询提现记录分页总数
     *
     * @param param
     * @return
     */
    @SelectProvider(type = SupplyFinanceDaoProvider.class, method = "queryWithdrawRecordCount")
    int queryWithdrawRecordCount(@Param("param") WithdrawRecordQueryParam param);

    /**
     * 查询提现记录分页数据
     *
     * @param param
     * @return
     */
    @SelectProvider(type = SupplyFinanceDaoProvider.class, method = "queryWithdrawRecordPage")
    List<WithdrawRecordDto> queryWithdrawRecordPage(@Param("param") WithdrawRecordQueryParam param);

    /**
     * 审核提现记录
     *
     * @param recordId
     * @param auditstate
     * @return
     */
    @Update("update yuhuang_withdraw_record set auditstate = #{auditstate},checkTime = sysdate() where id = #{recordId}")
    int checkWithdrawRecord(@Param("recordId") Long recordId, @Param("auditstate") Integer auditstate);

    /**
     * 再次转账
     *
     * @param withdrawRecord 提现记录仪
     * @return
     */
    @Update("update yuhuang_withdraw_record set state = 0,endTime= now(), flowNo=#{withdrawRecord.flowNo} where id = #{withdrawRecord.id} and state=4 ")
    int resetTransfer(@Param("withdrawRecord") WithdrawRecord withdrawRecord);

    /**
     * 查询
     *
     * @param recordId
     * @return
     */
    @Select("select * from yuhuang_withdraw_record where id = #{recordId} ")
    WithdrawRecord findWithdrawRecordById(Long recordId);

    /**
     * 处理失败
     *
     * @param recordId
     * @param state
     * @param dbState
     * @return
     */
    @Update("update yuhuang_withdraw_record set state = #{state},endTime= now() where id = #{recordId} and state = #{dbState} ")
    int dealFail(@Param("recordId") Long recordId, @Param("state") Integer state, @Param("dbState") Integer dbState);

    /**
     * 查询返利用户信息统计分页总数
     *
     * @param param
     * @return
     */
    @SelectProvider(type = SupplyFinanceDaoProvider.class, method = "queryRebateUserCount")
    int queryRebateUserCount(@Param("param") RebateUserQueryParam param);

    /**
     * 查询返利用户信息统计分页数据
     *
     * @param param
     * @return
     */
    @SelectProvider(type = SupplyFinanceDaoProvider.class, method = "queryRebateUserPage")
    List<RebateUserDto> queryRebateUserPage(@Param("param") RebateUserQueryParam param);

    /**
     * 通过订单号查询消费明细
     *
     * @param orderId 订单号
     * @param userId  会员id
     * @return 消费明细
     */
    @Select("select id,userId,consumeType,orderId,channel,money from yuhuang_user_consumption where orderId = #{orderId} and userId = #{userId} and consumeType in(2,4,5,9)")
    List<SupplyConsumption> querySupplyConsumption(@Param("orderId") String orderId, @Param("userId") Long userId);

    /**
     * 更新提现申请状态：提现表
     *
     * @param withdrawRecord 提现记录
     * @return 返回成功结果
     */
    @Update(" UPDATE yuhuang_withdraw_record " +
            "SET state =  #{withdrawRecord.state}, " +
            " endTime = NOW(), " +
            " remark =  #{withdrawRecord.remark} " +
            "WHERE " +
            " orderId =  #{withdrawRecord.orderId} " +
            "AND auditstate != 2 AND state in(0,1,4)")
    int updateWithdrawRecordRecall(@Param("withdrawRecord") WithdrawRecord withdrawRecord);

    /**
     * 修改消费明细  2：提现申请  5：提现失败 4: 提现成功 9:提现手续费
     *
     * @param id   明细id
     * @param type 明细类型
     * @return 修改行数
     */
    @Update("update yuhuang_user_consumption set consumeType = #{type} where id = #{id} and consumeType in(2,4,5,9)")
    int modifySupplyConsumption(@Param("id") Long id, @Param("type") int type);

    /**
     * 提现回调用户余额
     *
     * @param supplyBalance 余额
     * @param money         修改金额
     * @return 返回条数
     */
    @Update("  update yuhuang_supply_balance set balance = balance - #{money} ,freezebalance = freezebalance - #{money} " +
            " where userId = #{supplyBalance.userId} and (balance - #{money}) >= 0 and  freezebalance-#{money} >=0 ")
    int updateBalanceCallBack(@Param("supplyBalance") SupplyBalance supplyBalance, @Param("money") BigDecimal money);

    /**
     * 提现回调用户余额
     *
     * @param withdrawRecord 会员体现实体
     * @return 返回条数
     */
    @UpdateProvider(type = SupplyFinanceDaoProvider.class, method = "updateTransferFail")
    int updateTransferFail(@Param("withdrawRecord") WithdrawRecord withdrawRecord);

    /**
     * 查询提现记录操作日志
     *
     * @param withdrawId
     * @param type
     * @return
     */
    @Select(" SELECT " +
            " wl.admin, " +
            " wl.status, " +
            " wl.operate_time operateTime, " +
            " wl.withdraw_id withdrawId," +
            " wl.old_status oldStatus," +
            " wl.remark " +
            "FROM " +
            " yuhuang_withdraw_log wl " +
            "WHERE " +
            " wl.withdraw_id = #{withdrawId} and type=#{type}")
    List<WithdrawLog> queryWithdrawLog(@Param("withdrawId") Long withdrawId, @Param("type") WithdrawLogTypeEnum type);

    /**
     * 添加提现记录操作日志
     *
     * @param withdrawLog 提现记录操作日志
     * @return 返回记录
     */
    @Insert(" INSERT INTO yuhuang_withdraw_log ( " +
            " `admin`, " +
            " `withdraw_id`, " +
            " `status`," +
            "  type " +
            ") " +
            "VALUES " +
            " (#{withdrawLog.admin}, #{withdrawLog.withdrawId}, #{withdrawLog.status},#{withdrawLog.type}) ")
    int addWithdrawLog(@Param("withdrawLog") WithdrawLog withdrawLog);

    /**
     * 添加提现记录操作日志(加原始状态)
     *
     * @param withdrawLog 提现记录操作日志
     * @return 返回记录
     */
    @InsertProvider(type = SupplyFinanceDaoProvider.class, method = "addWithdrawLogs")
    int addWithdrawLogs(@Param("withdrawLog") WithdrawLog withdrawLog);

    /**
     * 查询会员提现明细
     *
     * @param param 查询参数
     * @return
     */
    @Select("SELECT " +
            " ysb.bank_no bankNo, " +
            " ysb.bank_salt bankSalt, " +
            " ywr.orderId, " +
            " ywr.flowNo, " +
            " ysu.account userAccount, " +
            " ysinfo.`name` userName, " +
            " ywr.withdrawChannel withdrawChannel, " +
            " ywr.price, " +
            " ywr.applytype, " +
            " ywr.startTime, " +
            " ywr.endTime, " +
            " ywr.state, " +
            " ywr.withdrawChannel, " +
            " ywr.servicePrice, " +
            " ysb.bank_name bankName, " +
            " a.`alipay` , " +
            " ywr.payBank " +
            "FROM " +
            " yuhuang_withdraw_record ywr " +
            " INNER JOIN yuhuang_sup_certificate ysi ON ysi.user_id=ywr.userId " +
            "INNER JOIN yuhuang_sup_user ysu ON ywr.userid = ysu.user_id " +
            "INNER JOIN yuhuang_sup_info ysinfo ON ysinfo.user_id = ysu.user_id " +
            "LEFT JOIN yuhuang_withdraw_bank ysb ON ywr.contractId=ysb.id AND ywr.withdrawChannel='bank' " +
            "LEFT JOIN yuhuang_sup_alipay a ON ywr.contractId=a.id AND ywr.withdrawChannel='alipay' " +
            "WHERE " +
            " ywr.endTime>=#{param.startTime} AND ywr.endTime<=#{param.endTime} " +
            "ORDER BY " +
            " ywr.id DESC")
    List<WithdrawRecordDto> findWithdrawRecord(@Param("param") WithdrawRecordQueryParam param);

    /**
     * 查询提现会员信息
     *
     * @param orderId 提现订单号
     * @return
     */
    @Select("SELECT r.withdrawChannel withdrawChannel,c.`name` certName,r.state,r.price,r.startTime,a.alipay ,b.bank_name bankName,b.bank_no transferNo,b.bank_salt bankSalt " +
            "  FROM yuhuang_withdraw_record r " +
            " INNER JOIN yuhuang_sup_certificate c ON c.user_id=r.userId " +
            " LEFT JOIN yuhuang_sup_alipay a ON r.contractId=a.id AND r.withdrawChannel='alipay' " +
            "LEFT JOIN yuhuang_withdraw_bank b ON r.contractId=b.id AND r.withdrawChannel='bank' WHERE  r.orderId=#{orderId}")
    DbWithdrawRecord queryDbWithdrawRecord(@Param("orderId") String orderId);
}
